package com.jamaskii.dictation;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jamaskii.ecdict.PronunciationStream;
import com.jamaskii.ecdict.Word;
import com.jamaskii.ecdict.WordBook;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class DictationActivity extends BaseActivity {

    private WordBook book=BookActivity.instance.book;
    private ArrayList<String> pronUS=new ArrayList<>();
    private ArrayList<String> pronGB=new ArrayList<>();
    private int cur=0;
    private TextView labelProgress;
    private boolean complete=false;
    private MediaPlayer player=new MediaPlayer();
    private int dPron=0;


    public int getStatueBarHeight(){
        int statusBarHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight = getResources().getDimensionPixelSize(height);
            return statusBarHeight;
        } catch (Exception e) {
            return 24;
        }
    }

    private void setTopPadding(){
        ConstraintLayout layout=findViewById(R.id.padding) ;
        ViewGroup.LayoutParams layoutParams=layout.getLayoutParams();
        layoutParams.height=getStatueBarHeight();
        layout.setLayoutParams(layoutParams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dictation);
        init();
    }

    private void init(){
        dPron=HomeActivity.instance.getDefaultPron();
        labelProgress=findViewById(R.id.label_progress);
        book=BookActivity.instance.book;
        loadPath();
        if(book.words.size()!=0){
            play(cur,dPron);
        }
        setTopPadding();
    }

    private void play(int index,int type){
        if(book.words.size()!=0 && cur==book.words.size()-1){
            complete=true;
        }
        labelProgress.setText((index+1)+"/"+BookActivity.instance.book.words.size());

        String path;
        if(type==0){
            path=pronUS.get(index);
        }else{
            path=pronGB.get(index);
        }
        try{
            if(path==null){
                Toast.makeText(this, "发音未找到", Toast.LENGTH_SHORT).show();
                return;
            }
            player.reset();
            player.setDataSource(path);
            player.prepare();
            player.start();
        }catch (Exception e){
            Toast.makeText(this, "播放出错", Toast.LENGTH_SHORT).show();
        }
    }

    public void onControlButtonsClick(View view){
        switch (view.getId()){
            case R.id.image_previous:
                if(cur==0){
                    return;
                }
                cur--;
                play(cur,dPron);
                break;
            case R.id.image_next:
                if(cur==BookActivity.instance.book.words.size()-1){
                    return;
                }
                cur++;
                play(cur,dPron);
                break;
            case R.id.image_speaker_gb:
                play(cur,1);
                break;
            case R.id.image_speaker_us:
                play(cur,0);
                break;
            case R.id.image_view:
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                Word word=BookActivity.instance.book.words.get(cur);
                builder.setTitle(word.name);
                builder.setMessage(word.translated);
                builder.create().show();
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            confirmBack();
            return false;
        }
        return false;
    }

    private void confirmBack(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("确定返回？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(complete){
                    book.times++;
                    SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MM/dd");
                    Date date = new Date(System.currentTimeMillis());
                    book.last=formatter.format(date);
                    book.save(HomeActivity.instance.wordBookStream.path);
                    HomeActivity.instance.loadBooks();
                    HomeActivity.instance.linkData();
                }
                finish();
            }
        });
        builder.setNegativeButton("取消",null);
        AlertDialog dialog=builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.themeColor));
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.themeColor));
    }

    public void onBackClick(View view){
        confirmBack();
    }

    private void loadPath(){
        pronGB.clear();
        pronUS.clear();
        for (Word word:book.words
             ) {
            String pathUS=BookActivity.instance.pronunciationStream.getPronunciation(word.name,0);
            String pathGB=BookActivity.instance.pronunciationStream.getPronunciation(word.name,1);
            pronUS.add(pathUS);
            pronGB.add(pathGB);
        }
    }

}